package com.example.client.conf;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.SecurityFilterChain;

import java.util.Map;

@Configuration
@EnableWebSecurity
public class OAuth2LoginSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .oauth2Login(oauth2 -> oauth2
                        .userInfoEndpoint(userInfo -> userInfo
                                .userService(this.oauth2UserService())));
        return http.build();
    }

    private OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService() {
        DefaultOAuth2UserService userService = new DefaultOAuth2UserService(){
            @Override
            public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
                //假设这里要将用户存到数据库
                OAuth2User oAuth2User = super.loadUser(userRequest);
                //userRequest 和 oAuth2User 中有大量的有用信息可以拿来使用 具体断点到这里看就行了
                //1 写个方法将 oAuth2User 和 userRequest 中有用的信息 转化成系统用户
                //2 将系统用户存入数据库
                Map<String, Object> attributes = oAuth2User.getAttributes();
                //3 可以在这里自定义一些信息放入 attributes 中
                return new DefaultOAuth2User(oAuth2User.getAuthorities(),attributes,userRequest
                        .getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName());
            }
        };

        return userService;
    }
}